<template>
    <el-dialog
            :close-on-click-modal="false"
            :model-value="bindApi.bindEmailState.visible"
            destroy-on-close
            title="绑定邮箱"
            width="480"
            @close="bindApi.onCloseBindEmail()"
    >

        <el-form
                ref="formRef"
                :model="bindApi.bindEmailState.form"
                :rules="rules"
                class="mr-10"
                label-width="100px"
                status-icon
        >
            <el-form-item
                    label="邮箱号"
                    prop="email"
            >
                <el-input
                        v-model="bindApi.bindEmailState.form.email"
                        clearable
                        placeholder="邮箱号"
                />
            </el-form-item>

            <el-form-item
                    label="验证码"
                    prop="code"
            >
                <i-send-mail-code
                        v-model:model-value="bindApi.bindEmailState.form.code"
                        :email="bindApi.bindEmailState.form.email"
                        class="fill-width"
                        hide-alter
                />
            </el-form-item>

            <el-form-item class="mb-0">
                <el-button type="primary" @click="onSubmit">绑定</el-button>
                <el-button @click="bindApi.onCloseBindEmail()">关闭</el-button>
            </el-form-item>

        </el-form>
    </el-dialog>
</template>

<script lang="ts" setup>
import {BindApi} from "~/api/system/account/bind.api";
import {reactive, ref} from "vue";
import {FormRules} from "element-plus";

interface Props {
    bindApi: BindApi;
}

const emits = defineEmits(["afterBind"]);
const {bindApi} = withDefaults(defineProps<Props>(), {});
const formRef = ref();

const rules = reactive<FormRules>({
    email: [{
        validator: (rule: any, value: any, callback: any) => {
            if (!value) {
                return callback(new Error("请输入邮箱号"));
            }
            const pattern = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
            if (!pattern.exec(value)) {
                return callback(new Error("请输入正确手机号"));
            }
            callback();
        }, trigger: "change",
    }],
    code: [{required: true, message: "请输入验证码", trigger: "blur"}],
});

async function onSubmit() {
    const values = await formRef.value.validate();
    if (values) {
        bindApi.onBindEmail().then(() => {
            emits("afterBind", true);
        }).catch(() => {
            emits("afterBind", false);
        });
    }
}
</script>

<style lang="scss" scoped>

</style>
